﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Windows.Forms;

namespace AutoUpgrade
{
    /// <summary>
    /// 更新程序的客户端请求实现
    /// </summary>
    public class UpgradeClient
    {
        /// <summary>
        /// 构建更新程序的客户端请求实现对象
        /// </summary>
        public UpgradeClient()
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        }

        /// <summary>
        /// 获取或设置更新系统需要所连接的服务器地址。
        /// </summary>
        public virtual string Host { get; set; }

        /// <summary>
        /// 获取或设置更新完成后启动的主程序名称。
        /// </summary>
        public virtual string StartupApplication { get; set; }

        /// <summary>
        /// 检查程序是否有更新包。
        /// </summary>
        /// <returns>如果程序有新的更新包，返回true，反之返回false。</returns>
        public virtual bool CheckUpgrade()
        {
            // 检测本地的版本文件
            if (File.Exists(GlobalSetting.LocalXmlFilePath))
            {
                string localXmlFileContent = File.ReadAllText(GlobalSetting.LocalXmlFilePath, System.Text.Encoding.UTF8);
                GlobalSetting.LocalConfig = new XmlVersionConfig(localXmlFileContent);
            }
            // 从服务器下载版本文件。
            string ServerXmlFileContent;
            var client = new WebClient();
            client.Encoding = System.Text.Encoding.UTF8;

            string url;
            if (GlobalSetting.Host.StartsWith("ftp"))
                url = $"{this.Host}{GlobalSetting.LocalConfigFileName}{GlobalSetting.Suffix}";
            else
                url = Path.Combine(this.Host, GlobalSetting.LocalConfigFileName) + GlobalSetting.Suffix;
            ServerXmlFileContent = client.DownloadString(url);
            GlobalSetting.ServerConfig = new XmlVersionConfig(ServerXmlFileContent);

            // 比较程序的主版本大小。
            if (GlobalSetting.LocalConfig == null)
                return true;
            return GlobalSetting.LocalConfig.MainVersion < GlobalSetting.ServerConfig.MainVersion;
        }

        /// <summary>
        /// 启动升级程序。
        /// </summary>
        public virtual void Upgrade()
        {
            string fileName = System.IO.Path.Combine(Application.StartupPath, "Upgrade.exe");
            if (System.IO.File.Exists(fileName))
            {
                Application.ExitThread();

                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.FileName = fileName;
                //设置启动动作,确保以管理员身份运行
                startInfo.Arguments = $"start {this.Host} {this.StartupApplication}";
                System.Diagnostics.Process.Start(startInfo);
            }
        }
    }
}
